import router from './router'
import type { RouteRecordRaw } from 'vue-router'
import { isRelogin } from '@/config/axios/service'
import { getAccessToken } from '@/utils/auth'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { useUserStoreWithOut } from '@/store/modules/user'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { getLoginConfig } from '@/api/login'
import { getLicense }from '@/api/license'
import { ca } from 'element-plus/es/locale'
const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()
// 路由不重定向白名单
const whiteList = [
  '/login',
  '/social-login',
  '/auth-redirect',
  '/bind',
  '/register',
  '/oauthLogin/gitee',
  '/loginloading',
  '/loginLoading',
  "/license"
]

// 路由加载前
router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  if (to.path === '/loginloading' || to.path === '/loginLoading' || to.path === '/loginFail') {
    next()
  } else if (getAccessToken()) {
    if (to.path === '/503') {
      next()
    }
    if (to.path === '/license') {
      try {
        const { data } = await getLicense()
        if (data?.endDate) {
          next('/')
        } else {
          next()
        }
      } catch (e) {
        next('/')
      }
      return false;
    }
    if (to.path === '/login') {
      next({ path: '/' })
    } else if (!(from.path != '/' && to.path == '/503')) {
        // 获取所有字典
        const dictStore = useDictStoreWithOut()    
        const userStore = useUserStoreWithOut()
        const permissionStore = usePermissionStoreWithOut()

        if (!dictStore.getIsSetDict) {
          try {
            await dictStore.setDictMap()
          } catch (e) {
            console.log(e)
          }
       
        }
        if (!userStore.getIsSetUser) {
          try{
            isRelogin.show = true
            await userStore.setUserInfoAction()
            isRelogin.show = false
            // 后端过滤菜单
            await permissionStore.generateRoutes()
            permissionStore.getAddRouters.forEach((route) => {
              router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
            })
          }catch(e) {
            console.log(e)
          }finally{
            const redirectPath = from.query.redirect || to.path
            const redirect = decodeURIComponent(redirectPath as string)
            const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
            next(nextData)
          }  
        } else {

          next()
        }
   
    }
  } else {
    if (to.path === '/license') { 
      try {
        // debugger;
        const { data } = await getLicense()
        if (data?.endDate) {
          return "/";
        } else {
          next();
        }
      } catch (e) {
        next('/')
      }
      return false;
    }else{
      try {
        const res = await getLoginConfig()
        if (!!res.data) {
          window.location.href = res.data
        } else if (whiteList.indexOf(to.path) !== -1) {
          next()
        } else {
     
          next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
        }
      } catch {
        if (whiteList.indexOf(to.path) !== -1){
          next()
        }
        next(`/login?redirect=${to.fullPath}`)
      }
    }
  

  }

})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
